import cv2

# 定义起始点和状态
drawing = False
ix, iy = -1, -1
image = cv2.imread('images/example.jpg')  # 修改为你的图片路径
clone = image.copy()

# 鼠标回调函数
def select_roi(event, x, y, flags, param):
    global ix, iy, drawing, image

    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        ix, iy = x, y

    elif event == cv2.EVENT_MOUSEMOVE and drawing:
        # 每次拖动都刷新图像，显示矩形框
        image = clone.copy()
        cv2.rectangle(image, (ix, iy), (x, y), (0, 255, 0), 2)
        cv2.imshow("images", image)

    elif event == cv2.EVENT_LBUTTONUP:
        drawing = False
        cv2.rectangle(image, (ix, iy), (x, y), (0, 255, 0), 2)
        roi = clone[min(iy, y):max(iy, y), min(ix, x):max(ix, x)]
        cv2.imshow("ROI", roi)

# 创建窗口并绑定鼠标事件
cv2.namedWindow("images")
cv2.setMouseCallback("images", select_roi)

cv2.imshow("images", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
